/*  Copyright (C) 2008  Alexander Blyzniuchenko (BlezAlex)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Aga.Controls.Tree;
using DC;

namespace MediaDC.Forms
{
    public partial class SearchForm : Form
    {
        private readonly TreeModel _searchResulstModel = new TreeModel();
        private readonly Dictionary<string, FileNode> _nodes = new Dictionary<string, FileNode>();
        private readonly List<HubClient> _aliveConnections = null; 

        public SearchForm()
        {
            _aliveConnections = HubConnectionManager.GetAliveConnections();

            foreach (HubClient client in _aliveConnections)
            {
                client.OnSearch += _hubClient_OnSearch;
            }

            InitializeComponent();

            fileTypeBox.SelectedIndex = 0;
            sizeRestrictionBox.SelectedIndex = 0;
            sizeUnitBox.SelectedIndex = 2;

            searchResults.Model = _searchResulstModel;
        }


        private void searchButton_Click(object sender, EventArgs e)
        {
            _searchResulstModel.Nodes.Clear();
            _nodes.Clear();
            long fileSize = 0;
            if (sizeBox.Text.Length > 0)
            {
                fileSize = int.Parse(sizeBox.Text) * (int)Math.Pow(1024, sizeUnitBox.SelectedIndex);
            }

            DoSearch(sizeBox.Text.Length > 0,
                              sizeRestrictionBox.SelectedIndex > 0,
                              fileSize,
                              (DcDataType)(fileTypeBox.SelectedIndex + 1),
                              searchBox.Text);
        }

        private void DoSearch(bool isSizeRestricted, bool isMinimumSize, long size, DcDataType type, string pattern)
        {
            foreach (HubClient client in _aliveConnections)
            {
                client.Search(isSizeRestricted, isMinimumSize, size, type, pattern);
            }
        }


        void _hubClient_OnSearch(object source, FoundFileEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new EventHandler<FoundFileEventArgs>(_hubClient_OnSearch), source, e);
            }
            else
            {
                lock (_nodes)
                {
                    if (_nodes.ContainsKey(e.File.TTH))
                    {
                        _nodes[e.File.TTH].Nodes.Add(new FileNode(e));
                        _nodes[e.File.TTH].Users++;
                    }
                    else
                    {
                        FileNode node = new FileNode(e);
                        _nodes.Add(e.File.TTH, node);
                        _searchResulstModel.Nodes.Add(node);
                    }
                }  
            }
        }

        private void searchResults_NodeMouseDoubleClick(object sender, TreeNodeAdvMouseEventArgs e)
        {
            FileNode node = (FileNode) (((TreeViewAdv) sender).SelectedNode).Tag;
            PreviewManager.RunPreview(node.File, node.NickName, node.HubConnectionID);
        }

        private void searchResults_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r' && searchResults.SelectedNode != null)
            {
                FileNode node = (FileNode) (((TreeViewAdv) sender).SelectedNode).Tag;
                PreviewManager.RunPreview(node.File, node.NickName, node.HubConnectionID);
            }
        }

        private void previewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (searchResults.SelectedNode != null)
            {
                FileNode node = (FileNode)(searchResults.SelectedNode).Tag;
                PreviewManager.RunPreview(node.File, node.NickName, node.HubConnectionID);
            }
        }

        private void getFileListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (searchResults.SelectedNode != null)
            {
                FileNode node = (FileNode)(searchResults.SelectedNode).Tag;
                HubConnectionManager.GetConnectedClient(node.HubConnectionID).RequestFileList(node.NickName);
            }
        }

        private void searchForAlternativeSourcesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (searchResults.SelectedNode != null)
            {
                FileNode node = (FileNode)(searchResults.SelectedNode).Tag;
                DoSearch(false, true, 0, DcDataType.TTH, node.TTH);
            }
        }

        private void SearchForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            foreach (HubClient client in _aliveConnections)
            {
                client.OnSearch -= _hubClient_OnSearch;
            }
            searchResults.Dispose();
        }

        private void downloadViaMangetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (searchResults.SelectedNode != null)
            {
                FileNode node = (FileNode)(searchResults.SelectedNode).Tag;
                PreviewManager.RunMagnetPreview(node.File);
            }
        }
    }
}
